<html>

<head>
	<title>子系统基础信息表列表</title>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<script src="../../static/react/react.development.js" type="text/javascript"></script>
	<script src="../../static/react/react-dom.development.js" type="text/javascript"></script>
	<script src="../../static/react/moment-with-locales.min.js" type="text/javascript"></script>
	<script src="../../static/react/babel.min.js" type="text/javascript"></script>
	<!-- antd -->
	<link href="../../static/react/antd/antd.min.css" rel="stylesheet" type="text/css" />
	<script src="../../static/react/antd/antd-with-locales.min.js" type="text/javascript"></script>
	<!-- axios -->
	<script src="../../static/react/axios.min.js" type="text/javascript"></script>
	<script src="../../static/react/qs.js" type="text/javascript"></script>
	<script src="../../static/react/lodash.min.js" type="text/javascript"></script>
	<script src="../../static/react/request.js" type="text/javascript"></script>
	<script src="../../ffres/dict/all.js" type="text/javascript"></script>
	<link href="../../static/react/common.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div id="app"> </div>
<script type="text/babel">
	// 请求后台相对路径
	const baseURL = "../../"
	// ant design 组件别名引用
	const { Row, Col, Form, Input, Select, DatePicker, Button, Table, Modal, message } = antd
	// 业务组件
	class App extends React.Component {
		constructor(props){
			super(props)
			// 在构造器中获取引用实例
			this.formRef = React.createRef()
			this.modelFormRef = React.createRef()
			// 将组件内函数绑定 this 上下文
			this.query = this.query.bind(this)
			this.reset = this.reset.bind(this)
			this.doAdd = this.doAdd.bind(this)
			this.doUpdate = this.doUpdate.bind(this)
			this.doDelete = this.doDelete.bind(this)
			this.doView = this.doView.bind(this)
			this.doActiveAgent = this.doActiveAgent.bind(this)
			this.doStopAgent = this.doStopAgent.bind(this)
			this.doMonitorAgent = this.doMonitorAgent.bind(this)
			this.handleModelClose = this.handleModelClose.bind(this)
			this.handleModlelOk = this.handleModlelOk.bind(this)
			this.tableSelect = this.tableSelect.bind(this)
			// 初始组件数据
			this.state = {
				list: [],
				pageInfo: {
					page: 1,
					size: 20,
					total: 0,
				},
				modelTitle: "",
				show: "",
				loading: false,
				opType: "", // 操作类型
				rowSelection: null,
				selectedRowKeys: []
			}
		}
		reset() {
			this.formRef.current.resetFields()
		}
		// 查询列表
		query(page){
			const self = this
			const pageInfo = this.state.pageInfo
			if (!page || typeof page != (typeof 1)) {
				pageInfo.page = 1;
			} else {
				pageInfo.page = page;
			}
			self.setState({pageInfo: pageInfo})
			API.request({
				baseURL: baseURL,
				method: "post",
				dataType: "form",
				url: "api/s/agent/infos",
				data: Qs.stringify({
					// 查询条件值通过 Form 获取
					...this.formRef.current.getFieldsValue(),
					// 分页信息
					...this.state.pageInfo
				})
			}).then(function(data){
				const pageInfo = self.state.pageInfo
				pageInfo.total = data.total
				// 回写 state 中的值后  通过 setState 通知 react 更新 DOM
				self.setState({
					list: data.rows.map(function(item, index){ return {...item, key: index}}),
					pageInfo: pageInfo,
				})
			})

		}
		tableSelect(selectedRowKeys, selectedRows) {
			if (selectedRows && selectedRows.length > 0) {
				this.setState({
					selectedRowKeys,
					rowSelection: selectedRows[0]
				})
			}
		}
		doAdd() {
			this.setState({ show: true, modelTitle: "代理节点信息新增", opType: "add"});
			setTimeout(()=>this.modelFormRef.current.resetFields(), 50)
		}
		doUpdate() {
			if (this.state.rowSelection){
				this.setState({ show: true, modelTitle: "代理节点信息修改", opType: "update"});
				setTimeout(()=>{
					this.modelFormRef.current.setFieldsValue(Object.assign(
							this.state.rowSelection,
							{
								startTime: moment(this.state.rowSelection.startTime, "YYYY-MM-DD HH:mm:ss"),
								stopTime: moment(this.state.rowSelection.stopTime, "YYYY-MM-DD HH:mm:ss"),
							}
					))
				}, 50)
			}else {
				message.error("请选择一条数据!")
			}

		}
		doDelete() {
			const self = this
			if (self.state.rowSelection) {
				Modal.confirm({
					title: '删除提示',
					content: '你确定要删除这条记录？',
					okText: '确认',
					cancelText: '取消',
					onOk() {
						return new Promise((resolve, reject) => {
							API.request({
								baseURL: baseURL,
								method: "delete",
								url: "api/s/agent/info",
								data: self.state.rowSelection,
							}).then(function(data){
								message.success("记录删除成功!")
								resolve()
								self.query(self.state.pageInfo.page)
								self.setState({
									selectedRowKeys: []
								})
							})
						});
					},
				});
			}else {
				message.error("请选择一条数据!")
			}
		}
		doView() {
			if (this.state.rowSelection){
				this.setState({ show: true, modelTitle: "代理节点信息详情", opType: "view"});
				setTimeout(()=>{
					this.modelFormRef.current.setFieldsValue(Object.assign(
							this.state.rowSelection,
							{
								startTime: moment(this.state.rowSelection.startTime, "YYYY-MM-DD HH:mm:ss"),
								stopTime: moment(this.state.rowSelection.stopTime, "YYYY-MM-DD HH:mm:ss"),
							}
					))
				}, 50)
			}else {
				message.error("请选择一条数据!")
			}

		}
		doActiveAgent(){
			const self =this;
			if (self.state.rowSelection){
				Modal.confirm({
					title: '激活提示',
					content: '是否确定要激活该执行节点？',
					okText: '确认',
					cancelText: '取消',
					onOk() {
						return new Promise((resolve, reject) => {
							API.request({
								baseURL: baseURL,
								method: "get",
								url: "api/s/srvs/cron/active/"+self.state.rowSelection.agentId,
								data: self.state.rowSelection,
							}).then(function(data){
								if (data.success){
									message.success("执行节点激活成功!")
								}else {
									message.error(data.message);
								}
								resolve()
								self.query(self.state.pageInfo.page)
								self.setState({
									selectedRowKeys: []
								})
							}).catch(function(error){
								message.warning("激活失败");
								self.setState({loading: false});
							})
						});
					},
				});
			}else {
				message.error("请选择一条数据!")
			}
		}
		doStopAgent(){
			const self =this;
			if (self.state.rowSelection){
				Modal.confirm({
					title: '停止提示',
					content: '是否确定要停止该执行节点？',
					okText: '确认',
					cancelText: '取消',
					onOk() {
						return new Promise((resolve, reject) => {
							API.request({
								baseURL: baseURL,
								method: "get",
								url: "api/s/srvs/cron/stop/"+self.state.rowSelection.agentId,
								data: self.state.rowSelection,
							}).then(function(data){
								if (data.success){
									message.success("执行节点停止成功!")
								}else {
									message.error(data.message);
								}
								resolve()
								self.query(self.state.pageInfo.page)
								self.setState({
									selectedRowKeys: []
								})
							}).catch(function(error){
								message.warning("停止失败");
								self.setState({loading: false});
							})
						});
					},
				});
			}else {
				message.error("请选择一条数据!")
			}
		}
		doMonitorAgent(){
			if (this.state.rowSelection){
				message.error("无此页面")
			}else {
				message.error("请选择一条数据!")
			}
		}


		handleModelClose() {
			this.setState({
				show: false
			})
			this.modelFormRef.current.setFieldsValue({})
		}
		handleModlelOk() {
			const self = this
			const { opType } = self.state
			self.setState({
				loading: true
			})
			if (opType == "add") {
				self.modelFormRef.current.validateFields().then(function(values){
					API.request({
						baseURL: baseURL,
						method: "post",
						url: "api/s/agent/info",
						data: Object.assign(values, {
							startTime: values.startTime ? values.startTime.format("YYYY-MM-DD HH:mm:ss") : "",
							stopTime: values.stopTime ? values.stopTime.format("YYYY-MM-DD HH:mm:ss") : "",
						})
					}).then(function(data){
						message.success("操作成功");
						self.setState({loading: false, show: false});
						self.query(self.state.pageInfo.page);
					}).catch(function(error){
						message.warning("操作失败");
						self.setState({loading: false});
					})
				}).catch(function(errorInfo){
					self.setState({loading: false})
				})
			} else if (opType == "update") {
				self.modelFormRef.current.validateFields().then(function(values){
					API.request({
						baseURL: baseURL,
						method: "put",
						url: "api/s/agent/info",
						data: Object.assign(values, {
							startTime: values.startTime ? values.startTime.format("YYYY-MM-DD HH:mm:ss") : "",
							stopTime: values.stopTime ? values.stopTime.format("YYYY-MM-DD HH:mm:ss") : "",
						})
					}).then(function(data){
						message.success("操作成功");
						self.setState({loading: false, show: false});
						self.query(self.state.pageInfo.page);
					}).catch(function(error){
						message.warning("操作失败");
						self.setState({loading: false});
					})
				}).catch(function(errorInfo){
					self.setState({loading: false});
				})
			} else {
				self.setState({loading: false, show: false})
			}
		}
		componentDidMount() {
			this.query()
		}
		render() {
			return (
					<div style={{padding: "15px"}}>
						{/* ref 创建 Form 实例的引用 */}
						<Form ref={this.formRef}>
							<Row>
								<Col span="8">
									<Form.Item label="代理节点标识" name="agentId" >
										<Input />
									</Form.Item>
								</Col>
								<Col className="btn-opt" style={{padding: "0 15px"}}>
									<Button type="primary" onClick={this.query}>查询</Button>
									<Button onClick={this.reset}>清空</Button>
								</Col>
							</Row>
						</Form>
						<div className="text-left btn-opt">
							<Button type="primary" onClick={this.doAdd} >新增</Button>
							<Button type="primary" onClick={this.doUpdate} >修改</Button>
							<Button type="primary" onClick={this.doDelete} >删除</Button>
							<Button type="primary" onClick={this.doView} >查看</Button>
							<Button type="primary" onClick={this.doActiveAgent} >激活</Button>
							<Button type="primary" onClick={this.doStopAgent} >停止</Button>
							<Button type="primary" onClick={this.doMonitorAgent} >监控</Button>
						</div>
						{ /*
                        dataSource 为列表数组
                        onChange Table 内嵌分页 页码切换回调函数
                        pagination Table 内嵌分页 配置 同 Pagination 组件API
                    */ }
						<Table dataSource={this.state.list} bordered
							   onChange={(pagination)=>this.query(pagination.current)}
							   pagination={{ position: ["bottomLeft"],
								   current: this.state.pageInfo.page,
								   pageSize: this.state.pageInfo.size,
								   total: this.state.pageInfo.total }}
							   rowSelection={{
								   type: "radio",
								   selectedRowKeys: this.state.selectedRowKeys,
								   onChange: this.tableSelect
							   }}>
							{ /* Table columns 的语法糖 最终还是给 Table 传递 columns 参数 dataIndex 便是对象属性  */ }
							<Table.Column title="代理节点标识" dataIndex="agentId"></Table.Column>
							<Table.Column title="代理节点名称" dataIndex="agentName"></Table.Column>
							<Table.Column title="代理节点状态" dataIndex="agentState"
										  render={(text, record)=>(formatter_INST_STATE(text))}></Table.Column>
							<Table.Column title="代理节点地址" dataIndex="agentUrl"></Table.Column>
							<Table.Column title="启动时间" dataIndex="startTime"></Table.Column>
							<Table.Column title="停止时间" dataIndex="stopTime"></Table.Column>
						</Table>

						<Modal
								title={this.state.modelTitle}
								visible={this.state.show}
								onCancel={this.handleModelClose}
								onOk={this.handleModlelOk}
								confirmLoading={this.state.loading}
								destroyOnClose={false}
								keyboard={false}
								style={{ top: 20 }}
								okText="确定"
								cancelText="取消"
								width={'100%'} >
							<Form ref={this.modelFormRef} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
								<Row>
									<Col span="12">
										<Form.Item label="代理节点标识" name="agentId"  rules={[{ required: true, message: "请输入代理节点标识" }]}>
											<Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
										</Form.Item>
									</Col>

									<Col span="12">
										<Form.Item label="代理节点名称" name="agentName" >
											<Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
										</Form.Item>
									</Col>

									<Col span="12">
										<Form.Item label="代理节点状态" name="agentState" >
											<Select allowClear placeholder="请选择"
													options={INST_STATE.map(function(item){
														return {label: item.cnname, value: item.enname}
													})}>
											</Select>
										</Form.Item>
									</Col>

									<Col span="12">
										<Form.Item label="代理节点地址" name="agentUrl" >
											<Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
										</Form.Item>
									</Col>

									<Col span="12">
										<Form.Item label="启动时间" name="startTime" >
											<DatePicker placeholder="请选择" showTime format="YYYY-MM-DD HH:mm:ss" />
										</Form.Item>
									</Col>

									<Col span="12">
										<Form.Item label="停止时间" name="stopTime" >
											<DatePicker placeholder="请选择" showTime format="YYYY-MM-DD HH:mm:ss" />
										</Form.Item>
									</Col>

								</Row>
							</Form>
						</Modal>
					</div>
			)
		}
	}
	ReactDOM.render(
			<antd.ConfigProvider locale={antd.locales.zh_CN}>
				<App />
			</antd.ConfigProvider>,
			document.getElementById('app')
	);
</script>
</body>
</html>